(function($){
    var _dialogBodyTmp = [
            '<div class="hvBox commonBg" style="width: 100%;height: 100%;overflow: auto;">',
                '<div class="mediaWrapper"></div>',
            '</div>'
        ].join(''),
        
        _loadErrorTmp = [
            '<div class="videoLoadErrorMsg">',
                'Load Video Failed, ',
                '<a target="_blank" href="<%=o.src%>">Click to download.</a>',
            '</div>'
        ].join(''),
        
        _videoItemTmp = [
            '<video style="background-color:#000;border-radius: 3px;" controls width="870px" height="520px" autoplay poster="<%=o.poster%>" >',
                '<source src="<%=o.src%>" type="<%=o.type%>" />',
            '</video>',
        ].join(''),
        
        _defaultConfig = {};
    
    var _MediaSliderDialog = function (config) {      
        var _this = this;   
        
        $.extend(this.config, _defaultConfig, config);     
        
        this.mediaIndex = 0;
        this.mediaCount = config['media'].length;
        
        this.setProps({
            size : {
                width : 900,
                height : 620
            }
        });
                
        if(this.mediaCount > 1){
            this.setProps({
                events : {
                    nav : function(direction){
                        _this.removeDialogLayer('video_load_error');
                        if(direction == 'left'){
                            if(_this.mediaIndex === 0){
                                _this.mediaIndex = _this.mediaCount;
                            }
                            _this.mediaIndex--;
                            _this.showMedia(_this.mediaIndex);
                        } else {
                            if(_this.mediaIndex === _this.mediaCount - 1){
                                _this.mediaIndex = -1;
                            }
                            _this.mediaIndex++;
                            _this.showMedia(_this.mediaIndex); 
                        }
                    }
                }
            });
        }
        
        if(this.mediaCount > 0){
            this.setProps({
                buttons : [
                    {   
                        props : 'actual|Actual Size',    
                        handler : function($btnObj){
                            //实际大小                
                            var $img = this.$wrapper.find('img');                            
                            _this.scale($img, 1);      
                        }
                    }, {   
                        props : 'zoomIn|Zoom In',    
                        handler : function($btnObj){
                            //放大                
                            var $img = this.$wrapper.find('img');
                            var scale = Math.min((parseFloat($img.attr('scale')) || 1) + .2, 20);
                            _this.scale($img, scale);         
                        }
                    }, {   
                        props : 'zoomOut|Zoom Out',    
                        handler : function($btnObj){
                            //缩小                
                            var $img = this.$wrapper.find('img');
                            var scale = Math.max((parseFloat($img.attr('scale')) || 1) - .2, .2);
                            _this.scale($img, scale);
                        }
                    }, {
                        props : 'download|Download',
                        handler : function(){
                            var currentMedia = _this.config['media'][_this.mediaIndex];
                            ujs.browser.file.downloadFromLink(currentMedia['vurl'] || currentMedia['url']);
                        }
                    }
                ]
            });
        }
        if(this.mediaCount > 1){
            _this.addArrow();
        }
        
        _this.addDialogContent(_dialogBodyTmp, function($dialogContent){
            //播放视频.
            $dialogContent.delegate('.playBtn', 'click', function(){
                _this.showMask('loading');
                var $mediaThumb = $(this).parent().find('img');
                var vurl = $mediaThumb.attr('vsrc');
                if(vurl){
                    var $mediaWrapper = $mediaThumb.parent(); 
                    $mediaWrapper.get(0).innerHTML = tmpl(_videoItemTmp, {
                        poster : $mediaThumb.attr('src'),
                        src : vurl,
                        type : 'video/mp4'
                    });
                    var $video = $mediaWrapper.find('video'); 
                    $video.on('canplay', function(){
                        _this.hideMask();
                    });          
                    $video.find('source').on('error', function(){
                        _this.hideMask();                    
                        _this.addDialogLayer( 'video_load_error', tmpl(_loadErrorTmp, {
                            src : vurl
                        }), function($loadErrorMsg){});
                    });
                }    
            });
            _this.showMedia(_this.mediaIndex);            
        });
    }.extend(ujs.ui.Dialog);
    
    _MediaSliderDialog.prototype.showMedia = function(mediaIndex){
        var _this = this;
        if(_this.config['media'][mediaIndex]['type'] == 'video'){
            //视频模式不显示功能按钮。
            _this.switchDialogButtons(['download']);
        } else {
            //显示图像操作功能按钮。
            _this.switchDialogButtons(['actual', 'zoomIn', 'zoomOut', 'download']);
        }
        this.$wrapper.find('.mediaWrapper').fadeOut(300, function(){
            _this.refreshTitle();            
            var playStr = '';
            if(_this.config['media'][mediaIndex]['type'] == 'video'){
                playStr = '<span class="playBtn large"></span>';
            }            
            $(this).html('<img class="mediaThumb" vsrc="{vurl}" src="{imgUrl}" />'.format({
                imgUrl : _this.config['media'][mediaIndex]['url'],
                vurl :  _this.config['media'][mediaIndex]['vurl'],
            }) + playStr).fadeIn(200);   
            
            var $image = $(this).find('img');
            ujs.browser.img.getSize($image.attr('src')).done(function(width, height){                
                $image.attr('trueWidth', width).attr('trueHeight', height);                
                var fixSize = new Size(width, height);                
                var bodySize = _this.getDialogBodyInnerSize();
                fixSize.constraint(bodySize.width - 20, bodySize.height - 20);                
                var scale = fixSize.width / width;               
                if(scale < 1){                        
                    _this.scale($image, scale);
                } else {
                    _this.scale($image, 1);
                }
            });      
        });
    };
    
    _MediaSliderDialog.prototype.refreshTitle = function(){
        this.setTitle(this.config['title'] + ' (' + (this.mediaIndex + 1) + '/' + this.mediaCount + ')');
    };
    
    _MediaSliderDialog.prototype.scale = function($img, scale){        
        $img.css({
           'width' : parseFloat($img.attr('trueWidth')) * scale,
           'height' : parseFloat($img.attr('trueHeight')) * scale
        });
        $img.attr('scale', scale);
    };
    
    //----------------------------------------------------------------------------------------------------------
    
    ujs.define('MediaSliderDialog', 'ujs.subjects.dialog', function(){
        return _MediaSliderDialog;
    });
        
})(jQuery);